import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 通用科技感表单基类，支持外部自定义风格
class TechFormBase extends StatefulWidget {
  final double value;
  final double height;
  final String unit;
  final String valueLabel;
  final IconData icon;
  final Color Function(double value) colorBuilder;
  final TechFormStatus? Function(double value) statusBuilder;
  final IconData? Function(double value) statusIconBuilder;
  final Gradient? backgroundGradient;
  final Gradient? valueGradient;
  final String? fontFamily;
  // 扩展组件
  final Widget? externalWidget;

  const TechFormBase({
    super.key,
    required this.value,
    required this.height,
    required this.unit,
    required this.valueLabel,
    required this.icon,
    required this.colorBuilder,
    required this.statusBuilder,
    required this.statusIconBuilder,
    this.backgroundGradient,
    this.valueGradient,
    this.fontFamily,
    this.externalWidget,
  });

  @override
  State<TechFormBase> createState() => _TechFormBaseState();
}

class _TechFormBaseState extends State<TechFormBase>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _valueAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _valueAnimation = Tween<double>(
      begin: 0,
      end: widget.value,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.elasticOut,
    ));
    _animationController.forward();
  }

  @override
  void didUpdateWidget(covariant TechFormBase oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.value != widget.value) {
      _animationController.reset();
      _valueAnimation = Tween<double>(
        begin: oldWidget.value,
        end: widget.value,
      ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeOut,
      ));
      _animationController.forward();
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final color = widget.colorBuilder(widget.value);
    final status = widget.statusBuilder(widget.value);
    final statusIcon = widget.statusIconBuilder(widget.value);
    final fontFamily = widget.fontFamily ?? 'Orbitron';
    return Container(
      width: screenWidth,
      height: widget.height,
      decoration: BoxDecoration(
        gradient: widget.backgroundGradient ??
            LinearGradient(
              colors: [Colors.black, Colors.blueGrey.shade900.withOpacity(0.1)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
      ),
      child: Stack(
        children: [
          Padding(
            padding: EdgeInsets.all(widget.height * 0.08),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildValueDisplay(screenWidth, color, fontFamily),
                Column(
                  children: [
                    statusIcon == null || status == null
                        ? Container()
                        : _buildStatusInfo(
                            screenWidth,
                            status,
                            statusIcon,
                            fontFamily,
                          ),
                    widget.externalWidget == null
                        ? Container()
                        : widget.externalWidget!,
                    SizedBox(height: widget.height * 0.09),
                  ],
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildValueDisplay(double width, Color color, String fontFamily) {
    return AnimatedBuilder(
      animation: _valueAnimation,
      builder: (context, child) {
        // 限制字体缩放，防止系统字体过大导致溢出
        final mediaQuery = MediaQuery.of(context);
        final limitedTextScaler =
            mediaQuery.textScaler.scale(1.0).clamp(1.0, 1.0);
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(
            textScaler: TextScaler.linear(limitedTextScaler),
          ),
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: width * 0.04,
              vertical: widget.height * 0.03,
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Flexible(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(
                            widget.icon,
                            color: color,
                            size: 20.w,
                            shadows: [
                              Shadow(
                                color: color.withOpacity(0.8),
                                blurRadius: 16,
                              ),
                            ],
                          ),
                          SizedBox(width: 5.w),
                          Text(
                            widget.valueLabel,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            style: TextStyle(
                              fontSize: widget.height * 0.04,
                              color: Colors.cyanAccent.withOpacity(0.8),
                              fontFamily: fontFamily,
                              fontWeight: FontWeight.w600,
                              letterSpacing: 1.2,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: widget.height * 0.012),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.baseline,
                        textBaseline: TextBaseline.ideographic,
                        children: [
                          ShaderMask(
                            shaderCallback: (Rect bounds) {
                              return LinearGradient(
                                colors: [
                                  Colors.cyanAccent,
                                  color,
                                  Colors.blueAccent,
                                  Colors.white,
                                ],
                                stops: const [0.0, 0.5, 0.8, 1.0],
                              ).createShader(bounds);
                            },
                            child: Text(
                              _valueAnimation.value.toStringAsFixed(1),
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                fontSize: widget.height * 0.25,
                                fontWeight: FontWeight.w900,
                                color: Colors.white,
                                fontFamily: fontFamily,
                                letterSpacing: 2.5,
                                shadows: [
                                  Shadow(
                                    color: color.withOpacity(0.7),
                                    blurRadius: 24,
                                  ),
                                  Shadow(
                                    color: Colors.cyanAccent.withOpacity(0.5),
                                    blurRadius: 12,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(width: width * 0.012),
                          Padding(
                            padding:
                                EdgeInsets.only(bottom: widget.height * 0.03),
                            child: Text(
                              widget.unit,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                fontSize: widget.height * 0.06,
                                color: Colors.cyanAccent.withOpacity(0.95),
                                fontFamily: fontFamily,
                                fontWeight: FontWeight.bold,
                                letterSpacing: 1.1,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildStatusInfo(double width, TechFormStatus status,
      IconData statusIcon, String fontFamily) {
    return Container(
      padding: EdgeInsets.all(widget.height * 0.04),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.3),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: status.color.withOpacity(0.15),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: widget.height * 0.02,
            height: widget.height * 0.02,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: status.color,
              boxShadow: [
                BoxShadow(
                  color: status.color.withOpacity(0.5),
                  blurRadius: 8,
                ),
              ],
            ),
          ),
          SizedBox(width: widget.height * 0.03),
          Text(
            status.text,
            style: TextStyle(
              fontSize: widget.height * 0.04,
              color: status.color,
              fontWeight: FontWeight.w500,
              fontFamily: fontFamily,
            ),
          ),
          const Spacer(),
          Icon(
            statusIcon,
            color: status.color,
            size: widget.height * 0.05,
          ),
        ],
      ),
    );
  }
}

class TechFormStatus {
  final String text;
  final Color color;
  const TechFormStatus(this.text, this.color);
}
